#!/use/bin/python
# coding=utf-8
# 早间开机 数据分析-健康作息-服务推送成功率15分钟/30分钟
import datetime
import pymysql

from dbutils.pooled_db import PooledDB


# proactive_service_conf 数据源
def getConfConnection():
    # 开发环境
    # pool = PooledDB(pymysql, 1, host='172.20.135.96', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_conf',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                db='proactive_service_conf', port=3307)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# proactive_service_data 数据源
def getDataConnection():
    # 开发环境
    #pool = PooledDB(pymysql, 1, host='172.20.151.80', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_data',port=3306)  # 1为连接池里的最少连接数

    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                    db='proactive_service_data', port=3407)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# 记录 数据分析-健康作息-服务推送成功率15分钟/30分钟
def insertStartupRate(date):
    try:
        conn, cur = getDataConnection()
        #判断 analysis_jkzx_push_rate 表是否已经存在当天 数据
        selectCountSql = """
                    select count(1) num from analysis_jkzx_push_rate t where 1=1  and t.ref_date =  '%s'
                """ % date
        cur.execute(selectCountSql)
        result = cur.fetchone()
        countNum = result[0]
        # 获取当日健康作息 弹窗数量
        pushNumSql = """
                    select count(DISTINCT(t.active_id)) from log_jkzx_yl t where 1=1 and t.result =1 and DATE_FORMAT(t.create_time, '%%Y-%%m-%%d') = '%s'
                """ % date;
        cur.execute(pushNumSql)
        pushNumResult = cur.fetchone()
        # 获取所有健康作息 弹窗数量
        pushAllNumSql = """
                           select count(1) from log_jkzx_yl t where 1=1 and t.result =1 
                       """ ;
        cur.execute(pushAllNumSql)
        pushAllNumResult = cur.fetchone()
        # 获取 当日 收到健康作息弹窗 15分钟内关机的设备量
        close15MinNumSql = """
               select count(DISTINCT(t.active_id)) from log_jkzx_poweroff t join log_jkzx_yl tt on t.active_id = tt.active_id and t.minute ='15' and DATE_FORMAT(t.create_time, '%%Y-%%m-%%d')= '%s'
                    and tt.result = 1 and DATE_FORMAT(t.create_time, '%%Y-%%m-%%d')= '%s'
                               """ % (date,date);
        cur.execute(close15MinNumSql)
        close15Result = cur.fetchone()
        # 获取 当日 收到健康作息弹窗 30分钟内关机的设备量
        close30MinNumSql = """
               select count(DISTINCT(t.active_id)) from log_jkzx_poweroff t join log_jkzx_yl tt on t.active_id = tt.active_id and t.minute ='30' and DATE_FORMAT(t.create_time, '%%Y-%%m-%%d')= '%s'
                    and tt.result = 1 and DATE_FORMAT(t.create_time, '%%Y-%%m-%%d')= '%s'
                               """ % (date,date);
        cur.execute(close30MinNumSql)
        close30Result = cur.fetchone()
        # 获取收到健康作息弹窗 15/30分钟关闭电视量及成功率
        success15MinRate = 0
        success30MinRate = 0
        close15MinNum =  close15Result[0]
        close30MinNum = close30Result[0]
        pushNum = pushNumResult[0]
        pushAllNum = pushAllNumResult[0]

        if pushNum != 0:
            if close15MinNum > pushNum:
                success15MinRate = 100
            else:
                success15MinRate = round(close15MinNum / pushNum, 4) * 100

            if close30MinNum > pushNum:
                success30MinRate = 100
            else:
                success30MinRate = round(close30MinNum / pushNum, 4) * 100

        if countNum == 0:
            logDetail = "%s日新增-健康作息弹窗数量为%s,总量为%s,15分钟内关闭数为%s,15分钟内关机成功率为%s,30分钟内关闭数为%s,30分钟内关机成功率为%s" %(
                date,pushNum,pushAllNum,close15MinNum,success15MinRate,close30MinNum,success30MinRate)
            print(logDetail)
            # 插入早间服务可见设备量
            insertSql = """insert into analysis_jkzx_push_rate(new_num,cumulate_num,close_15min_num,close_30min_num
            ,success_15min_rate,success_30min_rate,ref_date) 
                value(%s,%s,%s,%s,%s,%s,'%s')""" % (pushNum,pushAllNum,close15MinNum,close30MinNum,success15MinRate,success30MinRate,date)
            cur.execute(insertSql)
        else:
            logDetail ="%s日更新-健康作息弹窗数量为%s,总量为%s,15分钟内关闭数为%s,15分钟内关机成功率为%s,30分钟内关闭数为%s,30分钟内关机成功率为%s" %(
                date, pushNum, pushAllNum, close15MinNum, success15MinRate, close30MinNum, success30MinRate)
            print(logDetail)
            # 更新早间服务可见设备量
            updateSql = """
                update analysis_jkzx_push_rate set new_num = %s ,cumulate_num = %s,close_15min_num = %s ,close_30min_num = %s ,
                success_15min_rate = %s,success_30min_rate = %s , update_time = now()  where
                    ref_date = '%s' 
            """ % (pushNum, pushAllNum, close15MinNum, close30MinNum, success15MinRate, success30MinRate,date);
            cur.execute(updateSql)
        saveLog(logDetail, date)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()


# 记录 数据分析-健康作息-服务推送成功率15分钟/30分钟 --  月度
def insertStartupRateMonth(toDay,toMonthDay):
    try:
        conn, cur = getDataConnection()
        #判断 analysis_jkzx_push_rate 表是否已经存在当天 数据
        selectCountSql = """
                    select count(1) num from analysis_jkzx_push_rate t where 1=1  and t.ref_date =  '%s'
                """ % toMonthDay
        cur.execute(selectCountSql)
        result = cur.fetchone()
        countNum = result[0]
        # 计算本月的新增弹窗数据量
        pushNumSql = """
                           select sum(new_num) from analysis_jkzx_push_rate t where SUBSTR( t.ref_date, 1,7) = '%s' and t.ref_date != '%s' 
                       """ % (toMonthDay,toMonthDay);

        cur.execute(pushNumSql)
        pushNumResult = cur.fetchone()
        # 获取当日健康作息 弹窗数量 作为本月的弹窗数量
        pushAllNumSql = """
                    select cumulate_num from analysis_jkzx_push_rate t where ref_date = '%s' 
                """ % toDay;
        cur.execute(pushAllNumSql)
        pushAllNumResult = cur.fetchone()
        # 获取 本月 收到健康作息弹窗 15分钟内关机的设备量
        close15MinNumSql = """
                           select sum(close_15min_num) from analysis_jkzx_push_rate t where SUBSTR( t.ref_date, 1,7) = '%s' and t.ref_date != '%s' 
                       """ % (toMonthDay,toMonthDay);
        cur.execute(close15MinNumSql)
        close15Result = cur.fetchone()
        # 获取 本月 收到健康作息弹窗 30分钟内关机的设备量
        close30MinNumSql = """
                           select sum(close_30min_num) from analysis_jkzx_push_rate t where SUBSTR( t.ref_date, 1,7) = '%s' and t.ref_date != '%s' 
                       """ % (toMonthDay,toMonthDay);
        cur.execute(close30MinNumSql)
        close30Result = cur.fetchone()
        # 本月获取收到健康作息弹窗 15/30分钟关闭电视量及成功率
        success15MinRate = 0
        success30MinRate = 0
        close15MinNum =  close15Result[0]
        close30MinNum = close30Result[0]
        pushNum = pushNumResult[0]
        pushAllNum = pushAllNumResult[0]

        if pushNum != 0:
            if close15MinNum > pushNum:
                success15MinRate = 100
            else:
                success15MinRate = round(close15MinNum / pushNum,4)*100

            if close30MinNum > pushNum:
                success30MinRate = 100
            else:
                success30MinRate = round(close30MinNum / pushNum, 4) * 100

        if countNum == 0:
            logDetail = "%s月份新增-健康作息弹窗数量为%s,总量为%s,15分钟内关闭数为%s,15分钟内关机成功率为%s,30分钟内关闭数为%s,30分钟内关机成功率为%s" %(
                toMonthDay,pushNum,pushAllNum,close15MinNum,success15MinRate,close30MinNum,success30MinRate)
            print(logDetail)
            # 插入早间服务可见设备量
            insertSql = """insert into analysis_jkzx_push_rate(new_num,cumulate_num,close_15min_num,close_30min_num
            ,success_15min_rate,success_30min_rate,ref_date) 
                value(%s,%s,%s,%s,%s,%s,'%s')""" % (pushNum,pushAllNum,close15MinNum,close30MinNum,success15MinRate,success30MinRate,toMonthDay)
            cur.execute(insertSql)
        else:
            logDetail = "%s月份更新-健康作息弹窗数量为%s,总量为%s,15分钟内关闭数为%s,15分钟内关机成功率为%s,30分钟内关闭数为%s,30分钟内关机成功率为%s" %(
                toMonthDay, pushNum, pushAllNum, close15MinNum, success15MinRate, close30MinNum, success30MinRate)
            print(logDetail)
            # 更新早间服务可见设备量
            updateSql = """
                update analysis_jkzx_push_rate set new_num = %s ,cumulate_num = %s,close_15min_num = %s ,close_30min_num = %s ,
                success_15min_rate = %s,success_30min_rate = %s , update_time = now()  where
                    ref_date = '%s' 
            """ % (pushNum, pushAllNum, close15MinNum, close30MinNum, success15MinRate, success30MinRate,toMonthDay);
            cur.execute(updateSql)
        saveLog(logDetail, toMonthDay)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

# 获取当前日期
def todayYMD():
    today = datetime.datetime.now()-1
    # 获取想要的日期的时间
    re_date = (today).strftime('%Y-%m-%d')
    return re_date


# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m-%d')
    return re_date

# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getMonthdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m')
    return re_date

def saveLog(detail,ref_date):
    try:
        conn, cur = getDataConnection()
        jobId = 31
        jobName = '核心指标-健康作息-推送成功率'
        tableName = 'analysis_jkzx_push_rate'
        # 插入日志表
        saveLogSql = """insert into log_xxljob_analysis (job_id,job_name,detail,table_name,ref_date) 
                value(%s,'%s','%s','%s','%s')""" % (jobId,jobName,detail,tableName,ref_date)
        cur.execute(saveLogSql)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

if __name__ == '__main__':
    #today = todayYMD()
    date = getdate(1)
    monthdate = getMonthdate(1)
    #today = "2021-12-13"
    print ("%s 日期,执行<数据分析-健康作息-服务推送成功率15分钟/30分钟>报表" % date)
    insertStartupRate(date)
    insertStartupRateMonth(date, monthdate)
